import javax.swing.*;
import java.awt.*;
import java.awt.event.*;

public class GameListener extends MouseAdapter implements ActionListener,GoData {
    Graphics g = null;
    int chessFlag = 1;//1 黑旗 2 白旗 0 游戏未开始
    int [][] chessArr = new int [ROW+1][COL+1];
    int r;
    int c;

    @Override
    public void actionPerformed(ActionEvent e) {
        String action =e.getActionCommand();
        Object source = e.getSource();
        JButton btn =(JButton) source;
        if(action.equals("退出")) {
            System.exit(0);
        }


    }

    public void mousePressed(MouseEvent e) {
        int x = e.getX();
        int y = e.getY();
        int r = (y-Y+SIZE/2)/SIZE;
        int c = (x-X+SIZE/2)/SIZE;

        if(c>COL || r>ROW|| x<X-SIZE/2 || y<Y-SIZE/2){
            JOptionPane.showMessageDialog(null,"请在棋盘内落子");
            return;
        }
        if(chessArr[r][c]!=0){
            JOptionPane.showMessageDialog(null,"请勿重复落子");
            return;

        }


        chessArr[r][c]=chessFlag;//存储棋子
        if(chessFlag==1){
            g.setColor(Color.black);
            chessFlag=2;
        }else if (chessFlag==2){
            g.setColor(Color.white);
            chessFlag=1;
        }

        int chessX = c*SIZE + X- SIZE/2;
        int chessY = r*SIZE + Y- SIZE/2;
        g.fillOval(chessX,chessY,SIZE,SIZE);

    }
    public void mouseReleased(MouseEvent e) {
        int x = e.getX();
        int y = e.getY();
        if(chessFlag==1|| chessFlag==2){
            gameModelAI(x,y);
        }
    }
    private void gameModelAI(int x,int y) {
        int r = (y-Y+SIZE/2)/SIZE;
        int c = (x-X+SIZE/2)/SIZE;
        boolean isWin = GoWinUtils.isWin(chessArr,r,c);
        if(isWin) {
            JOptionPane.showMessageDialog(null, chessFlag==1?"白旗胜利":"黑旗胜利");
            chessFlag=0;//停止继续游戏

        }
    }

}